package main;

import conf.Config;
import javafx.util.Pair;
import service.ServiceContainer;
import util.FileUtil;
import util.Getopt;
import util.Global;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Server {

    public static void main(String[] args) throws InterruptedException, IOException {
        String cfgFile = FileUtil.GetCurPath() + "/config.yml";

        if (args.length > 0) {
            Getopt getopt = new Getopt(args);
            if (getopt.hasOption('f')){
                cfgFile = getopt.getOptionValue('f');
                System.out.println("f:" + cfgFile);
            }
        }

        Config cfg = new Config(cfgFile);
        Global.cfgFile=cfgFile;
        Global.limitFile=cfg.getNodeAttr(cfg.getNode1("file"),"limit");

        ArrayList<Pair<String, String>> Packages = new ArrayList<>();
        for (Object t : cfg.getNodeList("service")) {
            Packages.add(new Pair<>(cfg.getNodeAttr(t, "pkg"), cfg.getNodeAttr(t, "path")));
        }
        Pair[] basePackages = Packages.toArray(new Pair[Packages.size()]);
        if (basePackages.length > 0) {
            ServiceContainer serviceContainer = new ServiceContainer(basePackages);
            serviceContainer.start();
        }

        List<Thread> threads = new ArrayList<>();

        for (Object t : cfg.getNodeList("server")) {
            int port = 18000, timeout = 3000;
            String root = cfg.getNodeAttr(t, "root");
            if (("").equals(root)) root =  "./root";
            if (root.startsWith(".")) {
                root= FileUtil.GetCurPath()+root.substring(1);
            }
            System.out.println(root);
            try {
                port = Integer.parseInt(cfg.getNodeAttr(t, "port"));
                timeout = Integer.parseInt(cfg.getNodeAttr(t, "timeout"));
            } catch (NumberFormatException e) {
                System.err.println(e.getMessage());
            }
            Thread httpServerThread = new Thread(new MyServer(port,root,timeout)
                    , "HttpServer");
            httpServerThread.start();
            threads.add(httpServerThread);
            System.out.println("HttpServer started...");
        }

        for (Thread thread : threads
        ) {
            thread.join();
        }

    }

}
